package com.weai.exception;

import com.weai.dto.ApiResponse;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    
    /**
     * 处理资源未找到异常
     *
     * @param e 资源未找到异常
     * @return API响应
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiResponse<String> handleResourceNotFoundException(ResourceNotFoundException e) {
        log.error("资源未找到异常: {}", e.getMessage(), e);
        return ApiResponse.fail(HttpStatus.NOT_FOUND.value(), e.getMessage());
    }
    
    /**
     * 处理用户已存在异常
     *
     * @param e 用户已存在异常
     * @return API响应
     */
    @ExceptionHandler(UserAlreadyExistsException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<String> handleUserAlreadyExistsException(UserAlreadyExistsException e) {
        log.error("用户已存在异常: {}", e.getMessage(), e);
        return ApiResponse.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }
    
    /**
     * 处理方法参数无效异常
     *
     * @param e 方法参数无效异常
     * @return API响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.error("方法参数验证失败: {}", errorMessage, e);
        return ApiResponse.fail(HttpStatus.BAD_REQUEST.value(), errorMessage);
    }
    
    /**
     * 处理绑定异常
     *
     * @param e 绑定异常
     * @return API响应
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<String> handleBindException(BindException e) {
        String errorMessage = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.error("参数绑定失败: {}", errorMessage, e);
        return ApiResponse.fail(HttpStatus.BAD_REQUEST.value(), errorMessage);
    }
    
    /**
     * 处理约束违反异常
     *
     * @param e 约束违反异常
     * @return API响应
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<String> handleConstraintViolationException(ConstraintViolationException e) {
        String errorMessage = e.getConstraintViolations().stream()
                .map(violation -> violation.getMessage())
                .collect(Collectors.joining(", "));
        log.error("约束违反异常: {}", errorMessage, e);
        return ApiResponse.fail(HttpStatus.BAD_REQUEST.value(), errorMessage);
    }
    
    /**
     * 处理认证异常
     *
     * @param e 认证异常
     * @return API响应
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ApiResponse<String> handleAuthenticationException(AuthenticationException e) {
        String errorMessage = "认证失败";
        if (e instanceof BadCredentialsException) {
            errorMessage = "用户名或密码错误";
        }
        log.error("认证异常: {}", errorMessage, e);
        return ApiResponse.fail(HttpStatus.UNAUTHORIZED.value(), errorMessage);
    }
    
    /**
     * 处理访问拒绝异常
     *
     * @param e 访问拒绝异常
     * @return API响应
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ApiResponse<String> handleAccessDeniedException(AccessDeniedException e) {
        log.error("访问被拒绝: {}", e.getMessage(), e);
        return ApiResponse.fail(HttpStatus.FORBIDDEN.value(), "没有权限访问此资源");
    }
    
    /**
     * 处理通用异常
     *
     * @param e 通用异常
     * @return API响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<String> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ApiResponse.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部错误，请稍后再试");
    }
} 